package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author wangzhenjun
 * @date 2022/3/21 14:02
 */
@Configuration
public class MyRabbitmqConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * json序列化
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制rabbitmqtemplate
     */
    @PostConstruct
    public void initRabbitTemplate(){
        // 开启发送端确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 只确认消息抵达消息管理服务器
             * @param correlationData  当前消息的唯一关联数据（消息的唯一id）
             * @param ack 消息是否成功收到
             * @param cause  失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...correlationData{" + correlationData +"}====> ack:{" + ack + "} =====>cause:{" + cause +"}");
            }
        });
        // 开启发送端消息抵达队列的确认回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递到指定的队列。就触发这个失败回调
             * @param message  投递失败的消息详情
             * @param replyCode  回复的状态码
             * @param replyText  回复的文本内容
             * @param exchange   当时这个消息发送给那个交换机的
             * @param routingKey   消息所用的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("Fail ...message:"+message+"===>replycode:"+replyCode+"===>replyText:"+replyText+"===>exchange:"+exchange+"===>routingKey:"+routingKey);
            }
        });
    }
}
